// 云函数入口文件
const cloud = require('wx-server-sdk')
const request = require('request')
const fs = require('fs')
const path = require('path')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  const { remoteUrl, cloudPath } = event

  if (!remoteUrl || !cloudPath) {
    return {
      success: false,
      message: '远程URL和云存储路径都是必须的'
    }
  }

  try {
    // 创建临时文件路径
    const tmpDir = '/tmp'
    const tmpFilePath = path.join(tmpDir, `tmp_${Date.now()}.png`)

    // 下载远程图片
    console.log('准备下载远程图片:', remoteUrl)

    await new Promise((resolve, reject) => {
      request({
        url: remoteUrl,
        encoding: null, // 返回buffer
      })
        .pipe(fs.createWriteStream(tmpFilePath))
        .on('finish', () => {
          console.log('图片下载完成，保存到:', tmpFilePath)
          resolve()
        })
        .on('error', (err) => {
          console.error('下载图片失败:', err)
          reject(err)
        })
    })

    // 检查文件是否存在和大小
    const stats = fs.statSync(tmpFilePath)
    console.log('下载的临时文件大小:', stats.size)

    if (stats.size === 0) {
      return {
        success: false,
        message: '下载的文件大小为0'
      }
    }

    // 将临时文件上传到云存储
    console.log('准备上传到云存储路径:', cloudPath)
    const uploadResult = await cloud.uploadFile({
      cloudPath: cloudPath,
      fileContent: fs.readFileSync(tmpFilePath)
    })

    console.log('上传结果:', uploadResult)

    // 清理临时文件
    fs.unlinkSync(tmpFilePath)

    return {
      success: true,
      fileID: uploadResult.fileID
    }
  } catch (error) {
    console.error('处理图片失败:', error)
    return {
      success: false,
      message: error.message || '处理图片失败'
    }
  }
} 